package gui.parta;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class Q1 extends JFrame {
    public static void main(String[] args) {
        Q1 win = new Q1();
        win.setResizable(false);
        win.setBounds(10, 20, 450, 300);
        win.setTitle("Data Package Convert");
    }

    JLabel b1, b3;
    JTextField b2, b4;
    JButton b5, b6;

    public Q1() {
        init();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void init() {
        // 网格布局
        setLayout(null);
        JPanel panel = new JPanel();
        panel.setBounds(18, 18, 400, 220);
        panel.setLayout(new GridLayout(3, 2, 15, 15));
        // 组件
        b1 = new JLabel("Raw data:");
        b2 = new JTextField(10);
        b3 = new JLabel("Data package");
        b4 = new JTextField(10);
        b5 = new JButton("Data to packet");
        b5.addActionListener(new ToDataPacketMonitor(this));
        b6 = new JButton("Packet to data");
        b6.addActionListener(new ToDataPacketMonitor(this));
        panel.add(b1);
        panel.add(b2);
        panel.add(b3);
        panel.add(b4);
        panel.add(b5);
        panel.add(b6);
        add(panel);
    }
}

class ToDataPacketMonitor implements ActionListener {
    Q1 tf;

    public ToDataPacketMonitor(Q1 tf) {
        this.tf = tf;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if ("Data to packet".equals(actionCommand)) {
            String textV = tf.b2.getText();
            tf.b4.setText(DataPacket.convertToDataPacket(textV));
        }
        if ("Packet to data".equals(actionCommand)) {
            String textV = tf.b4.getText();
            try {
                tf.b2.setText(DataPacket.getDataFromDataPacket(textV));
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(tf, "非法数据包!", "提示", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
}


